#include "recbox.h"
#include "ui_recbox.h"
#include <QJsonObject>
#include <QList>

RecBox::RecBox(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::RecBox),
    row(1),
    col(4)
{
    ui->setupUi(this);
//    RecBoxItem* item = new RecBoxItem();
//    ui->reclistuplayout->addWidget(item);
}

RecBox::~RecBox()
{
    delete ui;
}

void RecBox::initRecBoxUi(QJsonArray data, int row)
{
    // 如果是两⾏，说明当前RecBox是主界⾯上的supplyMusicBox
    if(2 == row)
    {
        this->row = row;
        this->col = 8;
    }
    else
    {
        // 否则：只有⼀⾏，为主界⾯上recMusicBox
        ui->reclistdown->hide();
    }

    // 图⽚保存起来
    imageList = data;

    // 默认显⽰第0组
    currentIndex = 0;

    // 计算总共有⼏组图⽚
    count = imageList.size() / col;

    //在RecBox控件添加RecBoxItem
    createRecItem();
}

void RecBox::createRecItem()
{
    // 溢出掉之前旧元素
    QList<RecBoxItem*> recUpList = ui->reclistup->findChildren<RecBoxItem*>();
    for(auto e : recUpList)
    {
        ui->reclistuplayout->removeWidget(e);
        delete e;
    }

    QList<RecBoxItem*> recDownList = ui->reclistdown->findChildren<RecBoxItem*>();
    for(auto e : recDownList)
    {
        ui->reclistdownlayout->removeWidget(e);
        delete e;
    }

    // 创建RecBoxItem对象，往RecBox中添加
    //col
    //每次刷新是一页
    int index = 0;
    for(int i = currentIndex*col;i < col + currentIndex*col;i++)
    {
        RecBoxItem* item = new RecBoxItem();

        // 设置⾳乐图⽚与对应⽂本
        QJsonObject obj = imageList[i].toObject();
        item->setText(obj.value("text").toString());
        item->setImage(obj.value("path").toString());
        ui->reclistuplayout->addWidget(item);

        // 切分存放reclistdownlayout和reclistuplayout
        if(index >= col / 2 && row == 2)
        {
            ui->reclistdownlayout->addWidget(item);
        }
        else
        {
            ui->reclistuplayout->addWidget(item);
        }

        index++;
    }
}

void RecBox::on_btup_clicked()
{
    // 点击btUp按钮，显⽰前4张图⽚，如果已经是第⼀张图⽚，循环从后往前显⽰
    currentIndex--;
    if(currentIndex < 0)
    {
        currentIndex = 0;
    }
    createRecItem();
}

void RecBox::on_btdown_clicked()
{
    // 点击btUp按钮，显⽰前8张图⽚，如果已经是第⼀张图⽚，循环从后往前显⽰
    currentIndex++;
    if(currentIndex >= count)
    {
        currentIndex = 0;
    }
    createRecItem();
}
